#include "mydb.h"

MyDB::MyDB()
{
    myconfig=new MyConfig();
    mydb = QSqlDatabase::addDatabase("QMYSQL");
    mydb.setHostName(myconfig->getServer());
    mydb.setDatabaseName(myconfig->getDBName());
    mydb.setUserName(myconfig->getUsername());
    mydb.setPassword(myconfig->getPassword());
}

MyDB::~MyDB()
{
    delete myconfig;
}

bool MyDB::Mydb_ok()
{
    bool temp=false;
    if(!mydb.open())
        temp=false;
    else
        temp=true;
    mydb.close();
    return temp;
}

QString MyDB::SqlExec(QString str)
{
    QString rtv="";

    if(!mydb.open())
        return "0000";
    qDebug()<<str;
    QString q;
    QSqlQuery query;
    QString temp,password;
    QStringList list=str.split('|');
    switch(list[0].toInt())
    {
    case 5001:
        q="insert into user(username,password) value('"+list[1]+"','"+list[2]+"');";
        rtv="5100";
        if(query.exec(q))
            rtv+="|1";
        else
            rtv+="|0";
        qDebug()<<query.lastError();
        break;
    case 6001:
        q="select password from user where username='"+list[1]+"';";
        password=list[2];
        query.exec(q);
        if(query.next())
            temp=query.value(0).toString();
        //qDebug()<<temp;
        //qDebug()<<password;
        if(temp==password)
        {
            rtv="6000|"+list[1];
        }
        else
        {
            rtv="6011";
        }

        break;
    case 6101:
        q="select bmingzi from book where uno=(select no from user where username='"+list[1]+"');";
        rtv="6100";
        query.exec(q);
        while(query.next())
        {
            rtv+="|"+query.value(0).toString();
        }
        break;
    case 6201:
        q="select bmingzi,bzuozhe,bleibie,bjiage,bbeizhu,bzhuangtai from book where uno=(select no from user where username='"
                +list[1]+"') and bmingzi='"+list[2]+"';";
        rtv="6200";
        query.exec(q);
        if(query.next())
        {
            for(int i=0;i<6;i++)
                rtv+="|"+query.value(i).toString();
        }
        break;
    case 6301:
        q="insert into book(uno,bmingzi,bzuozhe,bleibie,bjiage,bbeizhu,bzhuangtai) value((select no from user where username='"
                +list[1]+"'),'"+list[2]+"','"+list[3]+"','"+list[4]+"',"+list[5]+",'"+list[6]+"','"+list[7]+"');";
        rtv="6300";
        if(query.exec(q))
            rtv+="|1";
        else
            rtv+="|0";
        qDebug()<<query.lastError();
        break;
    case 6401:
        q="delete from book where uno=(select no from user where username='"
                +list[1]+"') and bmingzi='"+list[2]+"';";
        rtv="6400";
        if(query.exec(q))
            rtv+="|1";
        else
            rtv+="|0";
        qDebug()<<query.lastError();
        break;
    default:
        rtv="9999";
    }
    mydb.close();
    qDebug()<<rtv;
    return rtv;
}
